<template>
  <div class="inviteFriends" ref="scrollEl">
    <canvas class="timeDistributionChart" id="timeDistributionChart"></canvas>
  </div>
</template>
<script setup name="inviteFriends">
import { useGlobalStore } from "~~/store/global";
import { getServeLog, removelog } from "../api/log.ts";
import { useDateFormat } from "@vueuse/core";

const globalStore = useGlobalStore();
const scrollEl = ref();
const route = useRoute();
console.log("页面参数:", route.query);

const isloadDone = ref(false); // 三方加载完成
loadScript(
  "https://cdn.jsdelivr.net/npm/chart.js",
  (val) => {
    if (val) isloadDone.value = true;
  },
  true,
  false
);

// 获取日志数据
const isRequestDone = ref(false); // 请求完成
const getServeLogRequest = () => {
  if (!route.query.errorId) return;

  getServeLog({
    pageSize: 1000,
    pageNumber: 1,
    errorId: route.query.errorId,
  }).then((res) => {
    // console.log("获取日志:", res);
    if (res) {
      const arr = res.list.filter((e) => {
        return e.errorId == route.query.errorId;
      });

      timestamps.value = arr.filter((e) => {
        return e.data.time;
      });
      console.log('--timestamps--',timestamps.value);
      
      isRequestDone.value = true;
    }
  });
};

// 示例时间戳数组（单位：毫秒）
const timestamps = ref([]);

const init = () => {
  // 获取当前时间
  const now = Date.now();
  const dayNum = 7;
  // 计算一周前的时间
  const oneWeekAgo = now - dayNum * 24 * 60 * 60 * 1000;

  // 初始化每小时的计数数组，包含7天，每天24小时
  const hoursCount = new Array(dayNum * 24).fill(0);

  // 遍历时间戳数组，统计每个小时的出现次数
  timestamps.value.forEach((timestamp) => {
    // console.log(
    //   "上报时间",
    //   useDateFormat(timestamp, "YYYY-MM-DD HH:mm:ss").value
    // );

    if (timestamp >= oneWeekAgo && timestamp <= now) {
      const date = new Date(timestamp);
      const dayIndex = Math.floor(
        (timestamp - oneWeekAgo) / (24 * 60 * 60 * 1000)
      );
      const hour = date.getHours();
      const index = dayIndex * 24 + hour;
      hoursCount[index]++;
    }
  });

  // 生成X轴标签
  const labels = [];
  for (let i = 0; i < dayNum; i++) {
    for (let j = 0; j < 24; j++) {
      labels.push(`Day ${i + 1} ${j}:00`);
    }
  }
  console.log("--labels--", labels);
  console.log("--hoursCount--", hoursCount);
  // 获取画布上下文
  const ctx = document.getElementById("timeDistributionChart").getContext("2d");

  // 创建图表
  const myChart = new Chart(ctx, {
    type: "line", // 线形图
    data: {
      labels: labels, // X轴标签，每小时一个
      datasets: [
        {
          label: "每小时出现次数",
          data: hoursCount, // 每小时的出现次数
          borderColor: "rgba(75, 192, 192, 1)", // 线条颜色
          backgroundColor: "rgba(75, 192, 192, 0.2)", // 填充颜色
          borderWidth: 1, // 线条宽度
        },
      ],
    },
    options: {
      responsive: true, // 使图表响应式.
      maintainAspectRatio: false, // 允许图表不保持宽高比
      scales: {
        x: {
          beginAtZero: true,
          ticks: {
            maxTicksLimit: 14, // 限制X轴标签数量，防止标签过多
          },
        },
        y: {
          beginAtZero: true,
        },
      },
    },
  });
};

watch([isRequestDone, isloadDone], (neweVal) => {
  if (neweVal[0] && neweVal[1]) init();
});

onMounted(() => {
  getServeLogRequest();
});
</script>
<style lang="scss" scoped>
.timeDistributionChart {
  width: 100vw;
  // height: 400 * 2px;
}
.inviteFriends {
  position: relative;
  background-color: #e1edfa;
  height: calc(var(--vh, 1vh) * 100);
  overflow-y: scroll;
  overflow-x: hidden;
  padding-bottom: calc(var(--safe-area-inset-bottom) + 110 * 2px);

  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    background: linear-gradient(180deg, #8dc4ff 0%, #c6fafc 75%, #c6fafc 100%);
    width: 100vw;
    height: calc(88 * 2px + 375 * 2px);
  }
  &-contentbg {
    position: relative;
    width: 100vw;
    background-color: #e1edfa;
  }
}
</style>
